from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import JsonResponse
import logging
import wave
import cv2
import json
import base64
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.asr.v20190614 import asr_client, models
# from . import transformjingweidu
import math



x_pi = 3.14159265358979324 * 3000.0 / 180.0;


pi = math.pi
es = 0.00669342162296594323  # 偏心率平方
a = 6378245.0  # 长半轴

# 纬度  精度
# GCJ-02 坐标转换成 BD-09 坐标
def bd_encrypt(gg_lat, gg_lon):
    x = gg_lon
    y = gg_lat
    z = math.sqrt(x * x + y * y) + 0.00002 * math.sin(y * x_pi);
    theta = math.atan2(y, x) + 0.000003 * math.cos(x * x_pi);
    bd_lon = z * math.cos(theta) + 0.0065;
    bd_lat = z * math.sin(theta) + 0.006;
    return [bd_lon, bd_lat]

# BD-09 坐标转换成GCJ-02
def bd_decrypt(bd_lat, bd_lon):
    x = bd_lon - 0.0065;
    y = bd_lat - 0.006;
    z = math.sqrt(x * x + y * y) - 0.00002 * math.sin(y * x_pi);
    theta = math.atan2(y, x) - 0.000003 * math.cos(x * x_pi);
    gg_lon = z * math.cos(theta);
    gg_lat = z * math.sin(theta);
    return [gg_lon, gg_lat]

def _transformlat(lng, lat):
    ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * math.sqrt(math.fabs(lng))
    ret += (20.0 * math.sin(6.0 * lng * pi) + 20.0 * math.sin(2.0 * lng * pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(lat * pi) + 40.0 * math.sin(lat / 3.0 * pi)) * 2.0 / 3.0
    ret += (160.0 * math.sin(lat / 12.0 * pi) + 320 * math.sin(lat * pi / 30.0)) * 2.0 / 3.0
    return ret

def _transformlng(lng, lat):
    ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * math.sqrt(math.fabs(lng))
    ret += (20.0 * math.sin(6.0 * lng * pi) + 20.0 * math.sin(2.0 * lng * pi)) * 2.0 / 3.0
    ret += (20.0 * math.sin(lng * pi) + 40.0 * math.sin(lng / 3.0 * pi)) * 2.0 / 3.0
    ret += (150.0 * math.sin(lng / 12.0 * pi) + 300.0 * math.sin(lng / 30.0 * pi)) * 2.0 / 3.0
    return ret

def GCJ02_to_WGS84(gcj_lng, gcj_lat):
    '''                                                               
    实现GCJ02坐标系向WGS84坐标系的转换
    :param gcj_lng: GCJ02坐标系下的经度
    :param gcj_lat: GCJ02坐标系下的纬度
    :return: 转换后的WGS84下经纬度
    '''
    dlat = _transformlat(gcj_lng - 105.0, gcj_lat - 35.0)
    dlng = _transformlng(gcj_lng - 105.0, gcj_lat - 35.0)
    radlat = gcj_lat / 180.0 * pi
    magic = math.sin(radlat)
    magic = 1 - es * magic * magic
    sqrtmagic = math.sqrt(magic)
    dlat = (dlat * 180.0) / ((a * (1 - es)) / (magic * sqrtmagic) * pi)
    dlng = (dlng * 180.0) / (a / sqrtmagic * math.cos(radlat) * pi)
    mglat = gcj_lat + dlat
    mglng = gcj_lng + dlng
    lng = gcj_lng * 2 - mglng
    lat = gcj_lat * 2 - mglat
    return [lng, lat]




logger = logging.getLogger(__name__)
# 填入自己的API密钥
secret_id = ""
secret_key = ""

num = 1
taskid=""

video_stream = ""
address= ""
# Create your views here.

def index(request):
    return render(request, "video/index.html", {})

def send_rtspmsg(request):
    global video_stream
    print("接收到客户端的请求:", request.GET)
    text = request.GET.get('text')
    print(text)
    video_stream = text
    return HttpResponse()


def send_msg(request):
    global address
    print("接收到客户端的请求:", request.GET)
    text = request.GET.get('text')
    print(text)
    address = text
    return HttpResponse()

def paizhao(request):
    global num
    print("接收到要视频流照片")
    rtsp_url = video_stream
    cap = cv2.VideoCapture(rtsp_url)
    ret, frame = cap.read()
    resized_frame = cv2.resize(frame, (600, 500))
    if not ret:
        print("打开对应的视频流有问题")
        return HttpResponse("", status=410)
    path = "static/images/duqian" + str(num) + ".jpg"
    cv2.imwrite(path, resized_frame)
    cap.release()
    num = num +1
    print("图片保存成功")
    return HttpResponse()

def audio_result(request):
    status = 0
    str=""
    global taskid
    print("taskid: ", taskid)
    params = {
        "TaskId":taskid
    }
    # 认证信息
    cred = credential.Credential(secret_id, secret_key)
    # HTTP配置
    httpProfile = HttpProfile()
    httpProfile.endpoint = "asr.tencentcloudapi.com"
    # 初始化客户端
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = asr_client.AsrClient(cred, "", clientProfile)
    # 发送请求
    req = models.DescribeTaskStatusRequest()
    req.from_json_string(json.dumps(params))
    resp = client.DescribeTaskStatus(req)
    data = json.loads(resp.to_json_string())
    status = data["Data"]["Status"]
    result = data["Data"]["Result"]
    str = result.split()[-1]
    if status == 2:
        file = open("static/note/audio.txt", "w")
        file.write(str)
        file.close()
    ret = {"mystatus": status, "result": str}
    return JsonResponse(ret)


def audio(request):
    global taskid
    if request.method == 'POST':
        with open("static/audio/duqian.mp3", "wb") as f:
            f.write(request.body)
        path1 = "static/audio/duqian.mp3"
        file1 = open(path1, "rb").read()
        text = base64.b64encode(file1).decode("utf-8")
        # 构造请求参数
        params = {
            "EngineModelType": "16k_zh",
            "ChannelNum": 1,
            "ResTextFormat": 0,
            "SourceType": 1,
            "Data":text,
            #"CallbackUrl":"https://43.136.99.209:9998/audio_result/"
        }
        # 认证信息
        cred = credential.Credential(secret_id, secret_key)
        # HTTP配置
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"
        # 初始化客户端
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = asr_client.AsrClient(cred, "", clientProfile)
        # 发送请求
        req = models.CreateRecTaskRequest()
        req.from_json_string(json.dumps(params))
        resp = client.CreateRecTask(req)
        # 解析返回结果
        print(resp.to_json_string())
        taskid = eval(resp.to_json_string())["Data"]["TaskId"]
    return HttpResponse()


def transformjingweidu(request):
    jingdu = request.GET.get('jingdu')
    weidu = request.GET.get('weidu')
    jingdu = float(jingdu)
    weidu = float(weidu)
    # 先转为GCJ02坐标
    jingdu, weidu = bd_decrypt(weidu, jingdu)
    # 再将GCJ02转为gps坐标
    jingdu, weidu = GCJ02_to_WGS84(jingdu, weidu)
    context = {
        "jingdu":jingdu,
        "weidu":weidu
    }
    return JsonResponse(context) #除了数据被序列化之外，还会加上一个响应头 application/json ，前端获取到数据的时候，jquery看到是json序列化之后，jquery自动转换了，不需要在自己手动json了
